<template>
  <div>
    <div>
      <div class="cards">
        <el-button type="primary" style="margin-right: 10px" @click="handleAdd">+ 新增</el-button>
        <el-button type="warning" style="margin-right: 20px" @click="delBatch">批量删除</el-button>
        <el-select v-model="value" placeholder="请选择品类" style="width: 240px;margin-right: 10px">
          <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
          />
        </el-select>
        <div class="demo-date-picker" style="margin-right: 10px">
          <div class="block" >
            <el-date-picker
                v-model="value2"
                type="daterange"
                start-placeholder="Start Date"
                end-placeholder="End Date"
            />
          </div>
        </div>
        <el-button type="primary" @click="load">查 询</el-button>
        <el-button type="primary" @click="rest">重 置</el-button>
      </div>
      <div class="card" style="margin-top: 10px">
        <el-table :data="data.tableData" @selection-change="handleSelectionChange" stripe>
          <el-table-column type="selection"  style="border: #666666; width:10px"></el-table-column>
          <el-table-column label="品类" prop="category"></el-table-column>
          <el-table-column label="名称" prop="name"></el-table-column>
          <el-table-column label="入库量(g)" prop="account"></el-table-column>
          <el-table-column label="入库人" prop="income_user"></el-table-column>
          <el-table-column label="入库日期" prop="income_date"></el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button @click="handleUpdate(scope.row)" type="primary" :icon="Edit" circle />
              <el-button @click="handleDelete(scope.row.id)" type="danger" :icon="Delete" circle />
            </template>
          </el-table-column>
        </el-table>
        <div style="margin-top: 10px">
          <el-pagination
              @current-change="load"
              @size-change="load"
              v-model:current-page="data.pageNum"
              v-model:page-size="data.pageSize"
              :page-sizes="[5,10,15,20]"
              background
              layout="total,sizes,prev,pager,next,jumper"
              :total="data.total"
          ></el-pagination>
        </div>
      </div>
      <!--新增-->
      <el-dialog v-model="data.formVisible" title="入库" width="500">
        <el-form :model="data.form" style="width: 400px; margin: 0 auto; display: flex; flex-direction: column; align-items: flex-start;">
          <!-- 设置label-width统一标签宽度 -->
          <el-form-item label="品类" label-width="80px"  style="margin-top: 20px">
            <el-select v-model="data.form.category" placeholder="请选择品类" style="width: 240px;margin-right: 10px">
              <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="名称" label-width="80px">
            <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入名称" style="width: 280px;"/>
          </el-form-item>
          <el-form-item label="入库量(g)" label-width="80px">
            <el-input v-model="data.form.account" autocomplete="off" placeholder="请输入库量" style="width: 280px;"/>
          </el-form-item>
          <el-form-item label="入库人" label-width="80px">
            <el-input v-model="data.form.income_user" autocomplete="off" style="width: 280px;"/>
          </el-form-item>
          <el-form-item label="日期" label-width="80px">
            <div class="demo-date-picker">
              <div class="block">
                <el-date-picker
                    v-model="data.form.income_date"
                    type="date"
                    :placeholder="data.form.income_date"
                />
              </div>
            </div>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="data.formVisible = false">取 消</el-button>
            <el-button type="primary" @click="save">保 存</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script setup>
import {reactive, onMounted} from "vue";
import {Search,Delete,Edit} from "@element-plus/icons-vue"
import { ref } from 'vue'
import request from '@/utils/request.js';
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  name: null,
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  userList: [],
  formVisible: false,
  form: {},
  ids: []
})

const value = ref('')
const value2 = ref([])

const options = [
  {
    value: '解表类',
    label: '解表类',
  },
  {
    value: '清热类',
    label: '清热类',
  },
  {
    value: '泻下类',
    label: '泻下类',
  },
  {
    value: '祛风湿类',
    label: '祛风湿类',
  },
  {
    value: '利水渗湿类',
    label: '利水渗湿类',
  },
  {
    value: '温理类',
    label: '温理类',
  },
  {
    value: '活血化瘀类',
    label: '活血化瘀类',
  },
  {
    value: '化痰止咳平喘类',
    label: '化痰止咳平喘类',
  },
  {
    value: '补虚类',
    label: '补虚类',
  },
]
const current_name = reactive({
  user:JSON.parse(localStorage.getItem('user-name'))
})
const load = () => {
  const [startDate, endDate] = value2.value;
  const params = {
    pageNum: data.pageNum,
    pageSize: data.pageSize,
  };
  if(value.value){
    params.name=value.value;
  }
  // 如果选择了日期范围，添加日期参数到请求中
  if (startDate && endDate) {
    params.startDate = startDate.toISOString().split('T')[0];
    params.endDate = endDate.toISOString().split('T')[0];
  }
  request.get('/income/findByCategoryAndDateRange', {
    params: params
  }).then(res => {
    console.log(res)
    data.tableData = res.data.content;
    data.total = res.data.page.totalElements;
  });
};

onMounted(() => {
  load()
})

// 重置
const rest = () => {
  data.name = null
  value.value = null
  value2.value = []
  load()
}

// 新增
const handleAdd = () => {
  data.formVisible = true;
  data.form = {};
  // 设置入库人的初始值
  if (current_name.user) {
    data.form.income_user = current_name.user.name;
  }
};

const save = () => {
  data.form.id ? update() : add()
}

const add = () => {
  request.post('income/addIncome',data.form).then(res => {
    console.log(res)
    if(res.code === 200){
      console.log(res)
      data.formVisible = false;
      ElMessage.success("添加成功")
      load()
    }else{
      ElMessage.error(res.message)
    }
  })
}

// 编辑
const update = () => {
  console.log(data.form)
  request.put('income/updateIncome', data.form).then(res => {
    if (res.code === 200) {
      data.formVisible = false;
      ElMessage.success("修改成功")
      load()
    } else {
      ElMessage.error(res.message)
    }
  })
}

// 删除
const handleDelete = (id) => {
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '温馨提示', { type: 'warning' }).then(() => {
    request.delete('income/delIncomeById/' + id).then(res => {
      console.log(res)
      if (res.code === 200) {
        ElMessage.success("删除成功")
        load()
      } else {
        ElMessage.error(res.message)
      }
    })
  }).catch()
}

// 编辑
const handleUpdate = (row) => {
  data.form = JSON.parse(JSON.stringify(row)) // 深拷贝
  data.formVisible = true
}

// 多选
const handleSelectionChange = (rows) => {
  console.log(rows)
  data.ids = rows.map(row => row.id)
  console.log(data.ids)
}

// 批量删除
const delBatch = () => {
  if (data.ids.length === 0) {
    ElMessage.warning('请选择数据')
    return
  }
  ElMessageBox.confirm('删除数据后无法恢复，您确认删除吗？', '温馨提示', { type: 'warning' }).then(() => {
    request.delete('income/deleteBatchType', { data: data.ids }).then(res => {
      if (res.code === 200) {
        ElMessage.success("删除成功")
        load()
      } else {
        ElMessage.error(res.message)
      }
    })
  }).catch()
}
</script>
<style scoped>
.demo-date-picker {
  display: inline-block;
  padding: 0;
  flex-wrap: wrap;
}
.demo-date-picker .block {
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}
.demo-date-picker .block:last-child {
  border-right: none;
}
.cards {
  background-color: white;
  padding: 10px;
  border-radius: 5px;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.12);
}
/* 调整表单元素的间距 */
.el-form-item {
  margin-bottom: 15px;
}
/* 可以对dialog的底部操作按钮部分进行样式微调 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 15px;
}
</style>